/* eslint react/prefer-stateless-function:0, react/prop-types:0 */

import React, { Component } from 'react';
import style from './style.css';
import { Icon } from 'antd';
import audioIcon from '../../images/audio.png';

export default class extends Component {

  constructor(props) {
    super(props);
  }

  state = {
    duration: '00:00',
    currentTime: '00:00',
    loading: false,
  };

  flag = false;

  play() {
    if (!this.flag) {
      this.setState({
        loading: true,
      });
    }
    const audio = document.getElementById(`audio-${this.props.id}`);
    if (audio.paused) {
      audio.play();
    } else {
      audio.pause();
    }
  }

  getFormatTime(time = 0) {
    let m = parseInt(time % 3600 / 60);
    let s = parseInt(time % 60);
    m = m < 10 ? "0" + m : m;
    s = s < 10 ? "0" + s : s;
    return m + ":" + s;
  }

  render() {
    const { id, src } = this.props;
    const { currentTime, duration, loading } = this.state;
    return (
      <div className={style.audio_panel} onClick={::this.play}>
        <div className={style.content}>
          <img className={style.content_img} src={audioIcon} />
          <div className={style.content_text}>{currentTime}/{duration}</div>
          {
            loading ? <Icon type="loading" style={{ marginLeft: '8px' }} /> : null
          }
        </div>
        <audio className="audio" preload="auto" id={`audio-${id}`}>
          <source src={src} />
          对不起，您的设备不支持播放语音。
        </audio>
      </div>
    );
  }

  componentDidMount() {
    const audio = document.getElementById(`audio-${this.props.id}`);

    audio.addEventListener('canplaythrough', () => {
      this.flag = true;
      this.setState({
        duration: this.getFormatTime(audio.duration),
        loading: false,
      });
    }, false);

    audio.addEventListener('timeupdate', () => {
      this.setState({
        currentTime: this.getFormatTime(audio.currentTime)
      });
    }, false);
  }
}